package com.ktjy.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.ktjy.goods.service.RealTimeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Collections;

/**
 * RealTimeServiceImpl
 *
 * @author LILIBO
 * @since 2025/5/31
 */
@Service
public class RealTimeServiceImpl implements RealTimeService {

    /**
     * API路径
     */
    private static final String API_PATH = "https://api.vvhan.com/api";

    /**
     * 发起HTTP请求的客户端
     */
    @Resource
    private RestTemplate restTemplate; // RestTemplate声明的Bean不要加@LoadBalanced注解，否则不能发起第三方固定URL的接口调用

    /**
     * 获取天气信息
     *
     * @param city 城市
     * @return 天气信息
     */
    @Override
    public Object weather(String city) {
        try {
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(API_PATH + "/weather");
            if (city != null && !city.isEmpty()) {
                // 如果城市不为空，则获取指定城市的天气信息
                builder.queryParam("city", city);
            }
            // 如果城市为空，则获取当前城市的天气信息
            return JSON.parse(restTemplate.getForObject(builder.build().toUriString(), String.class));
        } catch (RestClientException e) {
            return Collections.singletonMap("error", "第三方服务响应异常");
        }

    }

}
